#include "mainwindow.h"
#include "qftp.h"
#include "ui_mainwindow.h"

#include <config.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ftp = new QFtp(this);
    connect(ftp, &QFtp::commandFinished,this, &MainWindow::ftpCommandFinished);
    connect(ftp, &QFtp::listInfo,this, &MainWindow::addToList);
    connect(ftp, &QFtp::dataTransferProgress,this, &MainWindow::updateDataTransferProgress);


    connect(ui->treeWidget, &QTreeWidget::itemActivated, this, &MainWindow::processItem);

    ftp -> connectToHost("118.178.197.102",21);
    ftp -> login("ftp","ftp");

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::ftpCommandFinished(int commandId, bool error)
{
    qd << "ftpCommandFinished";
    if (ftp->currentCommand() == QFtp::ConnectToHost) qd << "QFtp::ConnectToHost";

    if (ftp->currentCommand() == QFtp::Login) {
        qd << "QFtp::Login";
        ftp->list();
    }

    if (ftp->currentCommand() == QFtp::Get) qd << "QFtp::Get";

    if (ftp->currentCommand() == QFtp::List) qd << "QFtp::List";
}

void MainWindow::addToList(const QUrlInfo &urlInfo)
{
    qd << "addToList";

//    ui->listWidget->addItems();
    QTreeWidgetItem *item = new QTreeWidgetItem;
    item->setText(0, urlInfo.name());
    item->setText(1, QString::number(urlInfo.size()));
    item->setText(2, urlInfo.owner());
    item->setText(3, urlInfo.group());
    item->setText(4, urlInfo.lastModified().toString("yyyy-MM-dd"));

    isDirectory[urlInfo.name()] = urlInfo.isDir();
    item->setIcon(0,QPixmap(urlInfo.isDir()? ":/images/images/dir.png" : ":/images/images/file.png"));
    ui->treeWidget->addTopLevelItem(item);
}

void MainWindow::updateDataTransferProgress(qint64 readBytes, qint64 totalBytes)
{
    qd << "updateDataTransferProgress";
}

void MainWindow::processItem(QTreeWidgetItem *item, int column)
{
    QString name = item->text(0);
    if (isDirectory.value(name)) {
        ui->treeWidget->clear();
        isDirectory.clear();
        currentPath += '/';
        currentPath += name;
        ftp->cd(currentPath);
        ftp->list();
    } else {

    }
}
